import { link } from 'fs';
import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { ActionSheetController, AlertController, ModalController, Platform } from '@ionic/angular';
import { EventService } from 'src/app/shared/service/event.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';

import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
import { NewInquiryPageModalComponent } from '../new-inquiry-page-modal/new-inquiry-page-modal.component';
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';

@Component({
    selector: 'app-call',
    templateUrl: './call.component.html',
    styleUrls: ['./call.component.scss']
})
//tslint:disable
export class CallComponent implements OnInit {
    @Input() tagData: any;
    ifLogin: any;
    defaultAvatar = '../../assets/img/head.png';
    mobileUUID = "callUUID";
    headPicUrlUUID = "headPicUrlUUID";
    onlineChatUUID = "onlineChatUUID";
    callBtnUUID = "callBtnUUID";
    constructor(
        private modalCtrl: ModalController,
        private modalController: ModalController,
        private actionSheetCtrl: ActionSheetController,
        private alertController: AlertController,
        private appGlobalService: AppGlobalService,
        private pageModalService: PageModalService,
        private eventService: EventService,
        private http: HttpService,
        public router: Router,
        private platform: Platform,
    ) {
        this.eventService.eventEmit.on("asyncGetPhoneNumber", (data) => {
            if (localStorage.getItem("asyncGetPhoneNumberTag")) {
                const tagData = JSON.parse(localStorage.getItem("asyncGetPhoneNumberTag"));
                localStorage.removeItem("asyncGetPhoneNumberTag");
                try {
                    this.appGlobalService.globalPhoneTagDataArray.push(tagData);
                    const len = this.appGlobalService.globalcallBtnUUIDArray.length - 1;
                    // phone-all-r  !tagData.data.onlineChat
                    // chat-all-r !tagData.data.call
                    if (tagData.onlineChat) {
                        this.tagData.data.onlineChat = tagData.onlineChat;
                    } else {
                        if (document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len])) {
                            this.addClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), "phone-all-r");
                        }
                        if (document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len])) {
                            document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len]).style.display = "none";
                        }


                    }

                    if (tagData.call) {
                        this.tagData.data.call = tagData.call;
                    } else {
                        if (document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len])) {
                            this.addClass(document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len]), "chat-all-r");
                        }
                        if (document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len])) {
                            document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]).style.display = "none";
                        }
                    }
                    this.tagData.data.mobile = tagData.mobile;
                    this.tagData.data.headPicurl = tagData.headPicurl;
                    if (document.getElementById(this.appGlobalService.globalMobileUUIDArray[len])) {
                        this.removeClass(document.getElementById(this.appGlobalService.globalMobileUUIDArray[len]), 'waitForLoadMobile');
                        document.getElementById(this.appGlobalService.globalMobileUUIDArray[len]).innerHTML = tagData.mobile;
                    }
                    document.getElementById(this.appGlobalService.globalHeadPicUrlUUIDArray[len]).setAttribute("src", tagData.headPicurl);
                    if (document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len])) {
                        document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]).innerHTML = tagData.call.label;
                        if (tagData.call && tagData.call.cssStyle) {

                            this.addClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), "big-btn");

                        } else if (tagData.call && tagData.call.className) {
                            this.addClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), tagData.call.className);
                        } else {
                            this.addClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), "phoneBg");
                        }

                    }
                    if (document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len])) {
                        this.addClass(document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len]), "chatBg");
                        document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len]).innerHTML = tagData.onlineChat.label;
                        if (tagData.onlineChat && tagData.onlineChat.className) {
                            this.addClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), tagData.onlineChat.className);
                        }
                    }
                } catch (error) {
                }
            }
        });
    }
    addClass(ele, value) {
        if (value && ele) {
            let curValue = this.getClass(ele);
            if (curValue && curValue.indexOf(value) === -1) {
                curValue = curValue + " " + value;
            }
            ele.setAttribute("class", curValue.trim());
        }
    }
    getClass(elem) {
        if (elem != null){
            return elem.getAttribute && elem.getAttribute("class") || "";
        } else {
           return "" 
        }
        
    }
    removeClass(ele, value) {
        if (value && ele) {
            let curValue = this.getClass(ele);
            if (curValue && curValue.indexOf(value) > -1) {
                curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
            }
            ele.setAttribute("class", curValue.trim());
        }
    }
    hasClass(ele, value) {
        let has = false;
        if (value && ele) {
            const curValue = this.getClass(ele);
            if (curValue && curValue.indexOf(value) > -1) {
                has = true;
            }
        }
        return has;
    }
    ngOnInit() {
        this.mobileUUID += new Date().getTime();
        this.headPicUrlUUID += new Date().getTime();
        this.onlineChatUUID += new Date().getTime();
        this.callBtnUUID += new Date().getTime();
        this.appGlobalService.globalMobileUUIDArray.push(this.mobileUUID);
        this.appGlobalService.globalHeadPicUrlUUIDArray.push(this.headPicUrlUUID);
        this.appGlobalService.globalonLineChatUUIDArray.push(this.onlineChatUUID);
        this.appGlobalService.globalcallBtnUUIDArray.push(this.callBtnUUID);
    }
    call() {
        const len = this.appGlobalService.globalPhoneTagDataArray.length - 1;
        if (this.appGlobalService.globalPhoneTagDataArray.length !== 0) {
            const lastObj = this.appGlobalService.globalPhoneTagDataArray[len];
            Object.assign(this.tagData.data, lastObj);
        }
        if (len >= 0 && !this.hasClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), 'phoneBg') && !this.hasClass(document.getElementById(this.appGlobalService.globalcallBtnUUIDArray[len]), 'big-btn')) {
            return;
        }
        if (this.tagData.data.call.enable === undefined || this.tagData.data.call.enable === true) {
            // 已收费
            const call = this.tagData.data.call;
            if (call.link && call.link.type && call.link.type === 'phone') {
                // 电话
                if (this.tagData.data.otherMobile) {
                    this.presentAction();
                } else {
                    this.presentAlertConfirm(this.tagData.data.mobile, this.tagData.data.nickName);
                }

            } else if (call.link && call.link.type && call.link.type === 'model') {
                // 处理包含登录的参数
                if (localStorage.getItem('loginStatus') !== 'true' && call.link.params !== undefined && call.link.params.oneLogin !== undefined && call.link.params.passwordLogin !== undefined) {

                    this.eventService.emit('openPage', JSON.stringify(call.link));
                    return
                }
                // 未收费
                const params = {
                    sessionId: localStorage.getItem("sessionId"),
                    pageId: call.link.target,
                    params: call.link.params
                };
                this.http.post('application/page', params, res => {
                    console.log(JSON.parse(res.script));
                    const tags = JSON.parse(res.script).views[0].tags;
                    const len = tags.length;
                    for (let i = 0; i < len; i++) {
                        const tmpTag = tags[i];
                        const tmpStyle = tags[i].style;
                        if (tmpStyle === 'appVipPopupTag') {
                            this.showRecommenMessageVip(tmpTag.data);
                            break;
                        } else if (tmpStyle === 'tipsDivTag') {
                            if (tmpTag.data && tmpTag.data.tipsDiv) {
                                tmpTag.data.tipsDiv.styleName = tmpTag.name;
                                this.showRecommenTip(tmpTag.data.tipsDiv);
                            } else {
                                this.showRecommenTip(tmpTag);
                            }
                            break;
                        } else if (tmpStyle === 'inquiry-page-style') {
                            this.presentAlertDialogConfirm(tmpTag);
                            break;
                        }
                    }
                });

            } else if (call.link && call.link.type && call.link.type === 'page') {
                this.appGlobalService.openPage(call.link);
            } else if (call.link && call.link.type && call.link.type === 'pageModal') {
                // this.appGlobalService.openPage(call.link);
                call.link.modalCss = 'auto-modal';
                this.pageModalService.openPage(call.link);
            } else {
                // 原列表电话逻辑
                if (this.tagData.data.otherMobile) {
                    this.presentAction();
                } else {
                    if (call.button) {
                        this.presentAlertConfirm(call.button.text1 + call.button.text2 + call.button.text3, '', call.button.sureText);
                    } else {
                        this.presentAlertConfirm(this.tagData.data.mobile, this.tagData.data.nickName);
                    }
                }
            }

        }
    }
    async showRecommenMessageVip(vipData) {
        const modal = await this.modalCtrl.create({
            showBackdrop: true,
            cssClass: 'recommend-modal-auto-heigth',
            component: RecommendModalComponent,
            componentProps: { vipData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
        });
        await modal.present();
        const modalData = await modal.onDidDismiss();
    }
    async presentAction() {
        const buttonsArr = [{
            text: '取消',
            cssClass: ['action-sheet-font-color', 'action-sheet-font-top'],
            handler: () => {
                actionSheet.dismiss();
            }
        }];
        if (this.tagData.data.otherMobile) {
            buttonsArr.unshift({
                text: this.tagData.data.otherMobile,
                cssClass: ['action-sheet-font-color'],
                handler: () => {
                    this.presentAlertConfirm(this.tagData.data.otherMobile, "");
                }
            });
        }
        if (this.tagData.data.mobile) {
            buttonsArr.unshift({
                text: this.tagData.data.mobile,
                cssClass: ['action-sheet-font-color'],
                handler: () => {
                    this.presentAlertConfirm(this.tagData.data.mobile, "");
                }
            });
        }
        const actionSheet = await this.actionSheetCtrl.create({
            mode: 'md',
            cssClass: 'match-padding',
            buttons: buttonsArr
        });
        await actionSheet.present();
    }
    async presentAlertConfirm(mobile, name, sureText?) {
        const alert = await this.alertController.create({
            header: this.tagData.nickName,
            message: name + " " + mobile,
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary'
                }, {
                    text: sureText ? sureText : '拨打',
                    handler: () => {
                        // 确定拨打后再发submit
                        const call = this.tagData.data.call;
                        if (call.button && call.button.submit) {
                            call.submit = call.button.submit;
                        }
                        if (call.submit) { // 表示已联系
                            const params = {
                                content: call.submit.content,
                                id: call.submit.id,
                                sessionId: localStorage.getItem("sessionId")
                            };
                            this.http.post("application/submit", params, res => {
                                if (res.message !== null) {
                                    this.appGlobalService.showToast(res.message, 1500, "middle");
                                    // buy 券
                                    if (call.button) {
                                        this.appGlobalService.reloadCurrentPage();
                                    }
                                }
                            });
                        }
                        if (!call.button) {
                            this.http.changeCallNumber(mobile);
                        }
                    }
                }
            ]
        });
        await alert.present();
    }
    async go() {
        const len = this.appGlobalService.globalPhoneTagDataArray.length - 1;
        if (this.appGlobalService.globalPhoneTagDataArray.length !== 0) {
            const lastObj = this.appGlobalService.globalPhoneTagDataArray[len];
            Object.assign(this.tagData.data, lastObj);
        }
        if (len >= 0 && !this.hasClass(document.getElementById(this.appGlobalService.globalonLineChatUUIDArray[len]), 'chatBg')) {
            return;
        }
        const item = this.tagData.data.onlineChat;
        const loginPage = this.tagData.data.onlineChat.loginPage;
        const cityId = JSON.parse(localStorage.getItem('position')) ? JSON.parse(localStorage.getItem('position')).code : 4403;
        if (localStorage.getItem('userId')) {
            // add by andrew.wen for // A手机登录账号，B手机再登录同一账号挤下来后，A手机点击商机详情的在线聊 进去了聊天页面。
            if (!localStorage.getItem('loginAccount')) {
                const pageParams = {
                    pageId: loginPage,
                    params: { skip: 0 },
                    sessionId: localStorage.getItem('sessionId')
                };
                localStorage.setItem('isDetailPage', 'true');
                this.appGlobalService.goToForward(pageParams);
                return;
            }
            if (item.link.type && item.link.type === 'chat') {// 收费
                if (item.submit) {
                    const params = {
                        content: item.submit.content,
                        id: item.submit.id,
                        sessionId: localStorage.getItem("sessionId")
                    };
                    this.http.post("application/submit", params, res => {
                        this.appGlobalService.showToast(res.message, 1500, "middle");
                        if (res.success) {
                            this.http.gotoChat(item);
                        }
                    });
                } else {
                    this.http.gotoChat(item);
                }
            } else if (item.link.type && item.link.type === 'model') {
                // 处理包含登录的参数
                if (localStorage.getItem('loginStatus') !== 'true' && item.link.params !== undefined && item.link.params.oneLogin !== undefined && item.link.params.passwordLogin !== undefined) {

                    this.eventService.emit('openPage', JSON.stringify(item.link));
                    return
                }
                const params = {
                    sessionId: localStorage.getItem("sessionId"),
                    pageId: item.link.target,
                    params: item.link.params
                };
                this.http.post('application/page', params, res => {
                    console.log(JSON.parse(res.script));
                    const tags = JSON.parse(res.script).views[0].tags;
                    const len = tags.length;
                    for (let i = 0; i < len; i++) {
                        const tmpTag = tags[i];
                        const tmpStyle = tags[i].style;
                        if (tmpStyle === 'appVipPopupTag') {
                            this.showRecommenMessageVip(tmpTag.data);
                            break;
                        } else if (tmpStyle === 'tipsDivTag') {
                            this.showRecommenTip(tmpTag);
                            break;
                        } else if (tmpStyle === 'inquiry-page-style') {
                            this.presentAlertDialogConfirm(tmpTag);
                            break;
                        }
                    }
                });
            } else if (item.link.type && item.link.type === 'page') {
                this.pageModalService.openPage(item.link);
            } else if (item.link.type && item.link.type === 'pageModal') {
                const modal = await this.modalController.getTop();
                if (modal) {
                    this.modalController.dismiss();
                }
                this.pageModalService.openPage(item.link);
            }
        } else if (loginPage) {
            const pageParams = {
                pageId: loginPage,
                params: { skip: 0 },
                sessionId: localStorage.getItem('sessionId')
            };
            localStorage.setItem('isDetailPage', 'true');
            this.appGlobalService.goToForward(pageParams);
        } else {
            // H5 跳转页面
            const modal = await this.modalController.getTop();
            if (modal) {
                this.modalController.dismiss();
            }
            // 蜂喔用户322 未登录的情况
            this.pageModalService.openPage(item.link);
        }
    }
    async showRecommenTip(tmpTagData) {
        const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: 'recommend-modal',
            component: RecommendModalComponent,
            componentProps: { tipData: tmpTagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
        });
        await modal.present();
        await modal.onDidDismiss().then((res) => {
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
        });
    }
    async presentAlertDialogConfirm(thisTagData) {
        try {
            const modal = await this.modalController.create({
                showBackdrop: true,
                cssClass: 'recommend-modal',
                animated: false,
                component: NewInquiryPageModalComponent,
                componentProps: { tagData: thisTagData.data }
            });
            await modal.present();
            await modal.onDidDismiss().then((res) => {

            });
        } catch (error) {
        }
    }
    copyStr(str) {
        if (this.appGlobalService.clientType === 'js') {    //如果是商户
            this.appGlobalService.copyString(str);
        }
    }
    ngOnDestroy(): void {
        if (this.appGlobalService.globalPhoneTagDataArray && this.appGlobalService.globalPhoneTagDataArray.length > 0) {
            this.appGlobalService.globalPhoneTagDataArray.pop();
            this.appGlobalService.globalMobileUUIDArray.pop();
            this.appGlobalService.globalHeadPicUrlUUIDArray.pop();
            this.appGlobalService.globalonLineChatUUIDArray.pop();
            this.appGlobalService.globalcallBtnUUIDArray.pop();
        }
    }
}
